<template>
  <div class="account-management">
    <!-- 页面标题和操作按钮 -->
    <div class="page-header">
      <div class="header-left">
        <h2>账户管理</h2>
        <p class="page-description">管理企业财务账户，包括银行账户、现金账户、虚拟账户等</p>
      </div>
      <div class="header-right">
        <el-button type="primary" @click="handleAdd">
          <el-icon><Plus /></el-icon>
          新增账户
        </el-button>
        <el-button @click="handleExport">
          <el-icon><Download /></el-icon>
          导出数据
        </el-button>
      </div>
    </div>

    <!-- 搜索和筛选区域 -->
    <el-card class="search-card" shadow="never">
      <el-form :model="searchForm" :inline="true" class="search-form">
        <el-form-item label="账户名称">
          <el-input
            v-model="searchForm.accountName"
            placeholder="请输入账户名称"
            clearable
            style="width: 200px"
          />
        </el-form-item>
        <el-form-item label="账户类型">
          <el-select
            v-model="searchForm.accountType"
            placeholder="请选择账户类型"
            clearable
            style="width: 150px"
          >
            <el-option label="银行账户" value="bank" />
            <el-option label="现金账户" value="cash" />
            <el-option label="虚拟账户" value="virtual" />
            <el-option label="支付宝" value="alipay" />
            <el-option label="微信支付" value="wechat" />
          </el-select>
        </el-form-item>
        <el-form-item label="账户状态">
          <el-select
            v-model="searchForm.status"
            placeholder="请选择状态"
            clearable
            style="width: 120px"
          >
            <el-option label="启用" value="active" />
            <el-option label="禁用" value="inactive" />
            <el-option label="冻结" value="frozen" />
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleSearch">
            <el-icon><Search /></el-icon>
            搜索
          </el-button>
          <el-button @click="handleReset">
            <el-icon><Refresh /></el-icon>
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>

    <!-- 数据统计卡片 -->
    <div class="stats-cards">
      <el-row :gutter="20">
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon bank">
                <el-icon><CreditCard /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.bankAccounts }}</div>
                <div class="stat-label">银行账户</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon cash">
                <el-icon><Money /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.cashAccounts }}</div>
                <div class="stat-label">现金账户</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon virtual">
                <el-icon><Wallet /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">{{ stats.virtualAccounts }}</div>
                <div class="stat-label">虚拟账户</div>
              </div>
            </div>
          </el-card>
        </el-col>
        <el-col :span="6">
          <el-card class="stat-card">
            <div class="stat-content">
              <div class="stat-icon total">
                <el-icon><Coin /></el-icon>
              </div>
              <div class="stat-info">
                <div class="stat-value">¥{{ stats.totalBalance }}</div>
                <div class="stat-label">总余额</div>
              </div>
            </div>
          </el-card>
        </el-col>
      </el-row>
    </div>

    <!-- 数据表格 -->
    <el-card class="table-card" shadow="never">
      <el-table
        :data="filteredTableData"
        v-loading="loading"
        stripe
        border
        style="width: 100%"
        @selection-change="handleSelectionChange"
      >
        <el-table-column type="selection" width="55" />
        <el-table-column prop="accountCode" label="账户编码" width="120" />
        <el-table-column prop="accountName" label="账户名称" min-width="150" />
        <el-table-column prop="accountType" label="账户类型" width="120">
          <template #default="{ row }">
            <el-tag :type="getAccountTypeTag(row.accountType)">{{ getAccountTypeName(row.accountType) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="bankName" label="开户银行" width="150" />
        <el-table-column prop="accountNumber" label="账户号码" width="180" />
        <el-table-column prop="balance" label="账户余额" width="120" align="right">
          <template #default="{ row }">
            <span class="balance-amount">¥{{ formatNumber(row.balance) }}</span>
          </template>
        </el-table-column>
        <el-table-column prop="status" label="状态" width="100">
          <template #default="{ row }">
            <el-tag :type="getStatusTag(row.status)">{{ getStatusName(row.status) }}</el-tag>
          </template>
        </el-table-column>
        <el-table-column prop="createTime" label="创建时间" width="160" />
        <el-table-column label="操作" width="200" fixed="right">
          <template #default="{ row }">
            <el-button type="primary" size="small" @click="handleEdit(row)">
              编辑
            </el-button>
            <el-button type="info" size="small" @click="handleView(row)">
              详情
            </el-button>
            <el-button type="danger" size="small" @click="handleDelete(row)">
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页 -->
      <div class="pagination-wrapper">
        <el-pagination
          v-model:current-page="pagination.currentPage"
          v-model:page-size="pagination.pageSize"
          :page-sizes="[10, 20, 50, 100]"
          :total="pagination.total"
          layout="total, sizes, prev, pager, next, jumper"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>

    <!-- 新增/编辑对话框 -->
    <el-dialog
      v-model="dialogVisible"
      :title="dialogTitle"
      width="600px"
      @close="handleDialogClose"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="formRules"
        label-width="100px"
      >
        <el-form-item label="账户名称" prop="accountName">
          <el-input v-model="formData.accountName" placeholder="请输入账户名称" />
        </el-form-item>
        <el-form-item label="账户类型" prop="accountType">
          <el-select v-model="formData.accountType" placeholder="请选择账户类型" style="width: 100%">
            <el-option label="银行账户" value="bank" />
            <el-option label="现金账户" value="cash" />
            <el-option label="虚拟账户" value="virtual" />
            <el-option label="支付宝" value="alipay" />
            <el-option label="微信支付" value="wechat" />
          </el-select>
        </el-form-item>
        <el-form-item label="开户银行" prop="bankName" v-if="formData.accountType === 'bank'">
          <el-input v-model="formData.bankName" placeholder="请输入开户银行" />
        </el-form-item>
        <el-form-item label="账户号码" prop="accountNumber">
          <el-input v-model="formData.accountNumber" placeholder="请输入账户号码" />
        </el-form-item>
        <el-form-item label="初始余额" prop="balance">
          <el-input-number
            v-model="formData.balance"
            :precision="2"
            :min="0"
            style="width: 100%"
            placeholder="请输入初始余额"
          />
        </el-form-item>
        <el-form-item label="账户状态" prop="status">
          <el-radio-group v-model="formData.status">
            <el-radio label="active">启用</el-radio>
            <el-radio label="inactive">禁用</el-radio>
          </el-radio-group>
        </el-form-item>
        <el-form-item label="备注" prop="remark">
          <el-input
            v-model="formData.remark"
            type="textarea"
            :rows="3"
            placeholder="请输入备注信息"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="dialogVisible = false">取消</el-button>
          <el-button type="primary" @click="handleSubmit">确定</el-button>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, reactive, computed, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Plus, Download, Search, Refresh, CreditCard, Money, Wallet, Coin } from '@element-plus/icons-vue'

// 响应式数据
const loading = ref(false)
const dialogVisible = ref(false)
const dialogTitle = ref('')
const isEdit = ref(false)
const formRef = ref()

// 搜索表单
const searchForm = reactive({
  accountName: '',
  accountType: '',
  status: ''
})

// 表单数据
const formData = reactive({
  id: null,
  accountName: '',
  accountType: '',
  bankName: '',
  accountNumber: '',
  balance: 0,
  status: 'active',
  remark: ''
})

// 表单验证规则
const formRules = {
  accountName: [
    { required: true, message: '请输入账户名称', trigger: 'blur' }
  ],
  accountType: [
    { required: true, message: '请选择账户类型', trigger: 'change' }
  ],
  accountNumber: [
    { required: true, message: '请输入账户号码', trigger: 'blur' }
  ],
  bankName: [
    { required: true, message: '请输入开户银行', trigger: 'blur' }
  ]
}

// 分页数据
const pagination = reactive({
  currentPage: 1,
  pageSize: 20,
  total: 0
})

// 统计数据
const stats = reactive({
  bankAccounts: 8,
  cashAccounts: 3,
  virtualAccounts: 5,
  totalBalance: '2,856,789.50'
})

// 表格数据
const tableData = ref([
  {
    id: 1,
    accountCode: 'ACC001',
    accountName: '工商银行基本户',
    accountType: 'bank',
    bankName: '中国工商银行',
    accountNumber: '6222021234567890123',
    balance: 1250000.00,
    status: 'active',
    createTime: '2024-01-15 09:30:00',
    remark: '企业基本账户'
  },
  {
    id: 2,
    accountCode: 'ACC002',
    accountName: '建设银行一般户',
    accountType: 'bank',
    bankName: '中国建设银行',
    accountNumber: '6217001234567890123',
    balance: 850000.00,
    status: 'active',
    createTime: '2024-01-20 14:20:00',
    remark: '一般存款账户'
  },
  {
    id: 3,
    accountCode: 'ACC003',
    accountName: '现金账户',
    accountType: 'cash',
    bankName: '',
    accountNumber: 'CASH001',
    balance: 50000.00,
    status: 'active',
    createTime: '2024-01-10 10:00:00',
    remark: '日常现金管理'
  },
  {
    id: 4,
    accountCode: 'ACC004',
    accountName: '支付宝企业账户',
    accountType: 'alipay',
    bankName: '',
    accountNumber: 'alipay@company.com',
    balance: 125000.00,
    status: 'active',
    createTime: '2024-02-01 16:45:00',
    remark: '线上支付账户'
  },
  {
    id: 5,
    accountCode: 'ACC005',
    accountName: '微信支付商户号',
    accountType: 'wechat',
    bankName: '',
    accountNumber: '1234567890',
    balance: 75000.00,
    status: 'active',
    createTime: '2024-02-05 11:30:00',
    remark: '微信支付收款'
  },
  {
    id: 6,
    accountCode: 'ACC006',
    accountName: '招商银行专用户',
    accountType: 'bank',
    bankName: '招商银行',
    accountNumber: '6214851234567890123',
    balance: 320000.00,
    status: 'active',
    createTime: '2024-02-10 09:15:00',
    remark: '专用存款账户'
  },
  {
    id: 7,
    accountCode: 'ACC007',
    accountName: '备用现金',
    accountType: 'cash',
    bankName: '',
    accountNumber: 'CASH002',
    balance: 20000.00,
    status: 'inactive',
    createTime: '2024-02-15 13:20:00',
    remark: '备用资金'
  },
  {
    id: 8,
    accountCode: 'ACC008',
    accountName: '虚拟账户001',
    accountType: 'virtual',
    bankName: '',
    accountNumber: 'VIR001',
    balance: 180000.00,
    status: 'active',
    createTime: '2024-02-20 15:40:00',
    remark: '内部虚拟账户'
  }
])

// 计算属性 - 过滤后的表格数据
const filteredTableData = computed(() => {
  let data = tableData.value
  
  if (searchForm.accountName) {
    data = data.filter(item => 
      item.accountName.toLowerCase().includes(searchForm.accountName.toLowerCase())
    )
  }
  
  if (searchForm.accountType) {
    data = data.filter(item => item.accountType === searchForm.accountType)
  }
  
  if (searchForm.status) {
    data = data.filter(item => item.status === searchForm.status)
  }
  
  pagination.total = data.length
  
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize
  return data.slice(start, end)
})

// 方法
const handleSearch = () => {
  pagination.currentPage = 1
}

const handleReset = () => {
  Object.assign(searchForm, {
    accountName: '',
    accountType: '',
    status: ''
  })
  pagination.currentPage = 1
}

const handleAdd = () => {
  dialogTitle.value = '新增账户'
  isEdit.value = false
  resetForm()
  dialogVisible.value = true
}

const handleEdit = (row) => {
  dialogTitle.value = '编辑账户'
  isEdit.value = true
  Object.assign(formData, row)
  dialogVisible.value = true
}

const handleView = (row) => {
  ElMessage.info(`查看账户详情: ${row.accountName}`)
}

const handleDelete = async (row) => {
  try {
    await ElMessageBox.confirm(
      `确定要删除账户 "${row.accountName}" 吗？`,
      '删除确认',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }
    )
    
    const index = tableData.value.findIndex(item => item.id === row.id)
    if (index > -1) {
      tableData.value.splice(index, 1)
      ElMessage.success('删除成功')
    }
  } catch {
    ElMessage.info('已取消删除')
  }
}

const handleSubmit = async () => {
  try {
    await formRef.value.validate()
    
    if (isEdit.value) {
      const index = tableData.value.findIndex(item => item.id === formData.id)
      if (index > -1) {
        Object.assign(tableData.value[index], formData)
        ElMessage.success('更新成功')
      }
    } else {
      const newAccount = {
        ...formData,
        id: Date.now(),
        accountCode: `ACC${String(tableData.value.length + 1).padStart(3, '0')}`,
        createTime: new Date().toLocaleString('zh-CN')
      }
      tableData.value.unshift(newAccount)
      ElMessage.success('添加成功')
    }
    
    dialogVisible.value = false
  } catch {
    ElMessage.error('表单验证失败')
  }
}

const handleDialogClose = () => {
  formRef.value?.resetFields()
  resetForm()
}

const resetForm = () => {
  Object.assign(formData, {
    id: null,
    accountName: '',
    accountType: '',
    bankName: '',
    accountNumber: '',
    balance: 0,
    status: 'active',
    remark: ''
  })
}

const handleExport = () => {
  ElMessage.success('导出功能开发中...')
}

const handleSelectionChange = (selection) => {
  console.log('选中的行:', selection)
}

const handleSizeChange = (size) => {
  pagination.pageSize = size
  pagination.currentPage = 1
}

const handleCurrentChange = (page) => {
  pagination.currentPage = page
}

// 工具方法
const getAccountTypeName = (type) => {
  const typeMap = {
    bank: '银行账户',
    cash: '现金账户',
    virtual: '虚拟账户',
    alipay: '支付宝',
    wechat: '微信支付'
  }
  return typeMap[type] || type
}

const getAccountTypeTag = (type) => {
  const tagMap = {
    bank: 'primary',
    cash: 'success',
    virtual: 'info',
    alipay: 'warning',
    wechat: 'success'
  }
  return tagMap[type] || ''
}

const getStatusName = (status) => {
  const statusMap = {
    active: '启用',
    inactive: '禁用',
    frozen: '冻结'
  }
  return statusMap[status] || status
}

const getStatusTag = (status) => {
  const tagMap = {
    active: 'success',
    inactive: 'info',
    frozen: 'danger'
  }
  return tagMap[status] || ''
}

const formatNumber = (num) => {
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: 2,
    maximumFractionDigits: 2
  }).format(num)
}

// 生命周期
onMounted(() => {
  // 初始化数据
  pagination.total = tableData.value.length
})
</script>

<style scoped>
.account-management {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 20px;
}

.header-left h2 {
  margin: 0 0 8px 0;
  color: #303133;
  font-size: 24px;
  font-weight: 600;
}

.page-description {
  margin: 0;
  color: #909399;
  font-size: 14px;
}

.header-right {
  display: flex;
  gap: 12px;
}

.search-card {
  margin-bottom: 20px;
}

.search-form {
  margin: 0;
}

.stats-cards {
  margin-bottom: 20px;
}

.stat-card {
  border: 1px solid #ebeef5;
  transition: all 0.3s;
}

.stat-card:hover {
  box-shadow: 0 4px 12px rgba(0, 0, 0, 0.1);
}

.stat-content {
  display: flex;
  align-items: center;
  padding: 10px 0;
}

.stat-icon {
  width: 50px;
  height: 50px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-right: 16px;
  font-size: 24px;
  color: white;
}

.stat-icon.bank {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
}

.stat-icon.cash {
  background: linear-gradient(135deg, #f093fb 0%, #f5576c 100%);
}

.stat-icon.virtual {
  background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
}

.stat-icon.total {
  background: linear-gradient(135deg, #43e97b 0%, #38f9d7 100%);
}

.stat-info {
  flex: 1;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #303133;
  line-height: 1;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  color: #909399;
}

.table-card {
  margin-bottom: 20px;
}

.balance-amount {
  font-weight: 600;
  color: #67c23a;
}

.pagination-wrapper {
  display: flex;
  justify-content: flex-end;
  margin-top: 20px;
}

.dialog-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .account-management {
    padding: 10px;
  }
  
  .page-header {
    flex-direction: column;
    gap: 16px;
  }
  
  .header-right {
    width: 100%;
    justify-content: flex-start;
  }
  
  .search-form {
    flex-direction: column;
  }
  
  .search-form .el-form-item {
    margin-right: 0;
    margin-bottom: 16px;
  }
  
  .stats-cards .el-col {
    margin-bottom: 16px;
  }
}
</style>